//
//  ShoppingCartViewController.swift
//  StoryDemo
//
//  Created by mac on 2019/7/3.
//  Copyright © 2019年 zhkj. All rights reserved.
//

import UIKit
import MJRefresh

class ShoppingCartViewController: UIViewController,JVShopcartFormatDelegate {
    
    var shopcartBotttomViewSettleBtnBlock:(() -> Void)?
    var shopcartBotttomViewAllSelectBlock:((_ isSelected:Bool) -> Void)?
    var shopcartBotttomViewDeleBtnBlock:(() -> Void)?
    var shopcartBotttomViewStarBtnBlock:(() -> Void)?
    
    @IBOutlet weak var lb_manage: UILabel!
    @IBOutlet weak var lb_count: UILabel!
    @IBOutlet weak var tableview: UITableView!
    @IBOutlet weak var uv_check: UIView!
    @IBOutlet weak var btn_check: UIButton!
    @IBOutlet weak var uv_clear: UIView!
    @IBOutlet weak var uv_submit: UIView!
    @IBOutlet weak var usv_clear: UIStackView!
    @IBOutlet weak var lb_delete: UILabel!
    @IBOutlet weak var lb_totalmoney: UILabel!
    @IBOutlet weak var lb_submit: UILabel!
    
    /**< 负责购物车逻辑处理 */
    lazy var shopcartFormat: JVShopcartFormat = {
        let shopcartFormat = JVShopcartFormat ()
        shopcartFormat.delegate = self
        shopcartFormat.viewController = self;
        return shopcartFormat
    }()
    
    /**< tableView代理 */
    lazy var shopcartTableViewProxy: JVShopcartTableViewProxy = {
        weak var weakSelf = self;
        let shopcartTableViewProxy = JVShopcartTableViewProxy ()
        shopcartTableViewProxy.shopcartProxyProductSelectBlock = {(isSelected,indexPath) in
            weakSelf?.shopcartFormat.selectProductAtIndexPath(indexPath: indexPath, isSelected: isSelected)
        }
        
        shopcartTableViewProxy.shopcartProxyBrandSelectBlock = {(isSelected,section) in
            weakSelf?.shopcartFormat.selectBrandAtSection(section: section, isSelected: isSelected)
        }
        
        shopcartTableViewProxy.shopcartProxyChangeCountBlock = {(count,indexPath) in
            weakSelf?.shopcartFormat.changeCountAtIndexPath(indexPath: indexPath, count: count)
        }
        
        shopcartTableViewProxy.shopcartProxyDeleteBlock = {(indexPath) in
            weakSelf?.shopcartFormat.deleteProductAtIndexPath(indexPath: indexPath)
        }
        
        shopcartTableViewProxy.shopcartProxyStarBlock = {(indexPath) in
            weakSelf?.shopcartFormat.starProductAtIndexPath(indexPath: indexPath)
        }
        
        return shopcartTableViewProxy
    }()
    override func viewDidLoad() {
        super.viewDidLoad()
        shopcartBotttomViewAllSelectBlock = {(isSelected) in
            self.shopcartFormat.selectAllProductWithStatus(isSelected: isSelected)
        }
        lb_manage.addOnClickListener(target: self, action: #selector(manage))
        btn_check.setImage(UIImage(named:"circle"), for: .normal)
        btn_check.setImage(UIImage(named:"yuangou"), for: .selected)
        btn_check.addOnClickListener(target: self, action: #selector(checkAll))
        uv_check.addOnClickListener(target: self, action: #selector(checkAll))
        lb_submit.addOnClickListener(target: self, action: #selector(submit))
        lb_submit.backgroundColor=UIColor.red
        lb_submit.textColor=UIColor.white
        lb_submit.layer.cornerRadius=5
        uv_submit.isHidden=false
        lb_delete.textColor=UIColor.red
        lb_delete.border(color: UIColor.red, width: 1, type: UIBorderSideType.UIBorderSideTypeAll, cornerRadius: 15)
        tableview.delegate = self.shopcartTableViewProxy
        tableview.dataSource = self.shopcartTableViewProxy
        tableview.register(UINib(nibName: "CartShopItemTableViewCell", bundle: nil), forHeaderFooterViewReuseIdentifier: "head")
        tableview.register(UINib(nibName: "CartItemTableViewCell", bundle: nil), forCellReuseIdentifier: "re")
        //refresh
        let header = TTRefreshHeader.init(refreshingBlock: {[weak self] in
            guard let strongSelf = self else{return}
            strongSelf.tableview.mj_header.endRefreshing()
            strongSelf.lb_totalmoney.text="￥\(0.0)"
            strongSelf.lb_submit.text="结算（\(0)）"
            strongSelf.btn_check.isSelected=false
            strongSelf.loadData()
        })
        tableview.mj_header=header
        tableview.separatorStyle = .none
        tableview.contentInset=UIEdgeInsets(top: 10, left: 0, bottom: 10, right: 0)
        
        loadData()
        // Do any additional setup after loading the view.
    }
    @objc func submit(){
        var cartItemIds=""
        for item in shopcartTableViewProxy.dataArray {
            for cartItem in item.Shop{
                if cartItem.isSelected{
                    cartItemIds+=cartItem.CartItemId!+","
                }
            }
        }
        if cartItemIds.count>0{
            cartItemIds=cartItemIds.prefix(cartItemIds.count-1).description
            print(cartItemIds)
            self.navigationController?.pushViewController(ConfirmOrderViewController(sku: nil,cartItemIds: cartItemIds), animated: true)
        }else{
            HUD.showText("请选择商品！")
        }
        
    }
    @objc func manage(){
        if uv_clear.isHidden {
            uv_clear.isHidden=false
            uv_submit.isHidden=true
            lb_manage.text="完成"
        }else{
            uv_clear.isHidden=true
            uv_submit.isHidden=false
            lb_manage.text="管理"
        }
    }
    @objc func checkAll(){
        btn_check.isSelected = !btn_check.isSelected
        if shopcartBotttomViewAllSelectBlock != nil{
            shopcartBotttomViewAllSelectBlock!(btn_check.isSelected)
        }
    }

    func loadData(){
        var d = ["userkey":userkey,
                 "app_key":app_key,
                 "timestamp":getTimestamp()
            ] as! [String : String]
        let sign=SignTopRequest(params: d)
        d["sign"]=sign
        AlamofireHelper.get(url: GetCartProduct, parameters: d, successHandler: {[weak self](res)in
            HUD.dismiss()
            guard let ss = self else {return}
            var count=0
            ss.shopcartTableViewProxy.dataArray.removeAll()
            for item in CartShop.init(json: res).Shop!{
                count+=item.count
                ss.shopcartTableViewProxy.dataArray.append(ShopBean.init(Shop: item))
            }
            ss.shopcartFormat.shopcartListArray=ss.shopcartTableViewProxy.dataArray
            ss.lb_count.text="共\(count)件"
            ss.tableview.reloadData()
        }){[weak self] (error) in
            HUD.dismiss()
            guard let ss = self else {return}
        }
    }
    
    
    
    //MARK: ************** JVShopcartFormatDelegate 逻辑处理代理方法
    func shopcartFormatAccountForTotalPrice(totalPrice: Float, totalCount: Int, isAllSelected: Bool){
//        shopcartBottomView.configureShopcartBottomViewWithTotalPrice(totalPrice: totalPrice, totalCount: totalCount, isAllSelected: isAllSelected)
//        
//        shopcartTableViewProxy.dataArray = shopcartFormat.shopcartListArray
//
        btn_check.isSelected=isAllSelected
        lb_totalmoney.text="￥\(totalPrice)"
        lb_submit.text="结算（\(totalCount)）"
        tableview.reloadData()
    }
    func shopcartFormatHasDeleteAllProducts(){
        
    }
    
    
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
